package cluster

import (
	"fmt"

	"gddgame.cc/galaxy/utils/def"
)

type Socket interface {
	def.ID
	Add(component def.Component) error    // 添加组件
	Delete(component def.Component) error // 移除组件
}

type SocketInstance struct {
	id         string
	components def.ComponentSlice
	instance   interface{}
}

func NewSocket(id string, instance interface{}) *SocketInstance {
	s := &SocketInstance{
		id:         id,
		components: []def.Component{},
		instance:   instance,
	}

	return s
}

func (s *SocketInstance) ID() string {
	return s.id
}

func (s *SocketInstance) Instance() interface{} {
	return s.instance
}

func (s *SocketInstance) Add(component def.Component) error {
	index := s.components.Search(component)
	if index >= 0 {
		return fmt.Errorf("Component %#v is exits", component)
	}
	err := component.Join(s)
	if err != nil {
		return err
	}
	s.components = s.components.Append(component)
	return nil
}

func (s *SocketInstance) Delete(component def.Component) error {
	id := component.ID()
	index := s.components.Search(component)
	if index == -1 {
		return fmt.Errorf("Component %s is not exits", id)
	}
	err := component.Remove(s)
	if err != nil {
		return err
	}
	s.components = s.components.Remove(index)
	return nil
}

func (s *SocketInstance) Group(category string) []def.Component {
	c := make([]def.Component, 0)
	for _, component := range s.components {
		if component.Group(category) {
			c = append(c, component)
		}
	}
	return c
}
